from django.shortcuts import render
from rest_framework.views import APIView  # 导入APIView类，用于视图类的基类
from rest_framework.response import Response  # 导入Response类，用于返回响应数据
from rest_framework import status  # 导入status模块，用于返回状态码
from Apis.serializers import ProductModelSerializer 
from product.models import Product  # 导入Product模型，用于操作数据库
from rest_framework.authentication import BasicAuthentication,SessionAuthentication,TokenAuthentication 
from rest_framework.permissions import IsAuthenticated,AllowAny,IsAdminUser
from Drf_api.paginations import ProductPageNumberPagination


# Create your views here.



# 访问数据，需要认证用户身份。通过认证后，才能访问数据。
class ProductApiView(APIView):
    # 使用分页器类
    pagination_class = ProductPageNumberPagination
    
    # 认证用户
    authentication_classes = [BasicAuthentication]
    # 权限类
    permission_classes = [IsAuthenticated]
    # 限流
    throttle_scope = "product"
   
    
    # authorization  Basic aGs6MTIzNDU2   Basic认证+用户名和密码的base64编码
    
    def get(self,request,*args,**kwargs):
        # 获取查询参数
        request.query_params.get("pk")
        
        # ============================================================
        # 获取路径参数 ?product_name=xxx
        # product_name = request.query_params.get("product_name")
        # print(product_name)  # 打印product_name的值，用于调试
        # product = Product.objects.filter(product_name=product_name)
        #========================================================================
        # 获取当前请求的用户对象
        user = request.user.id
        
        # 根据模型查询数据
        product = Product.objects.all()
        
        # 调用分页器，分页一般是作为列表的时候处理
        paginator = self.pagination_class()
        # 对分页数据进行筛选
        page = paginator.paginate_queryset(product,request)
        # 对分页数据处理
        if page is not None:
            ser = ProductModelSerializer(page,many=True)
            # 返回分页数据响应
            return paginator.get_paginated_response(ser.data)
        
        # 将查询到的数据传递给序列化器进行处理
        ser = ProductModelSerializer(product,many=True)
        # 返回响应
        return Response(ser.data,status=status.HTTP_200_OK)
    
    def post(self,request,*args,**kwargs):
        # 1.获取前端传递来的的数据
        ser = ProductModelSerializer(data=request.data)
        # 2.将数据传递给序列化器进行处理
        # 3.保存数据
        if ser.is_valid(raise_exception=True):
            ser.save()
        # 4.返回响应
            return Response({"message":"商品添加成功！","data":ser.data},status=status.HTTP_201_CREATED)
        